﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace zichan.Filters
{
    /// <summary>
    /// 权限拦截
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class AuthorizeFilterAttribute : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext == null)
                throw new ArgumentNullException("filterContext");


            //忽略对Login登录页的权限判定
            string path = filterContext.HttpContext.Request.Path.ToLower();
            if (path == "/account/login")
                return;

            //根据验证判断进行处理
            int r = AuthorizeCore(filterContext);
            if (r == 4 || (r == 3 && path == "/home"))
                return;
            if (r != 4)
            {
                if (filterContext.IsChildAction == false)
                {
                    filterContext.HttpContext.Response.StatusCode = 401;
                    filterContext.Controller.TempData["error"] = (r == 2 ? "请先登录" : "页面未授权");
                    filterContext.Result = new RedirectResult("/account/login?returnUrl=" + filterContext.HttpContext.Request.Path);
                }
                else
                    filterContext.Result = new ContentResult { Content = @"抱歉,你不具有当前操作的权限！" };
            }
        }

        //权限判断业务逻辑
        protected virtual int AuthorizeCore(ActionExecutingContext filterContext)
        {
            //判定用户是否登录
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
                return 1;

            if (((FormsIdentity)filterContext.HttpContext.User.Identity).Ticket.UserData != "admin")
                return 2;

            string uid = filterContext.HttpContext.User.Identity.Name.Split(':')[0];
            string controllerName = filterContext.RouteData.Values["controller"].ToString().ToLower();
            string actionName = filterContext.RouteData.Values["action"].ToString().ToLower();
            if (Common.PowerHelp.GetUserMenu().Count(m => m.Controller == controllerName && m.Action == actionName) == 0)
                return 3;

            return 4;
        }
    }
}